package com.db.report.exchange;

import com.db.protocol.ExchangeProtocol;
import com.db.protocol.ReportFixProtocol;
import com.db.protocol.exception.ParseProtocolException;
import com.db.protocol.message.ReportMessage;
import com.db.transport.exchange.SessionExchange;
import com.db.transport.exchange.listener.SessionExchangeListener;

import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.logging.Logger;

/**
 * @author nulls.narik
 */
public class ReceiverExchange implements SessionExchangeListener {

    private static Logger logger = Logger.getLogger(ReceiverExchange.class.getName());

    private final SessionExchange sessionExchange;
    private final ExchangeProtocol protocol;
    private Thread threadSessionExchange;

    public ReceiverExchange(SessionExchange sessionExchange) {
        this.sessionExchange = sessionExchange;
        this.sessionExchange.addListener(this);
        this.protocol = new ReportFixProtocol();
        this.listeners = new CopyOnWriteArraySet<ReceiverExchangeListener>();
    }

    public void start() {
        logger.info(String.format("Start receiver for exchange"));
        threadSessionExchange = new Thread(sessionExchange);
        threadSessionExchange.start();
    }

    public void shutdown() {
        sessionExchange.shutdown();
    }

    @Override
    public void newMessage(String message) {
        try {
            logger.info(String.format("New message from exchange: %s", message));
            ReportMessage reportMessage = protocol.parseReport(message);
            newMessage(reportMessage.getClientID(), reportMessage);
        } catch (ParseProtocolException e) {
            logger.warning(String.format("Error when receiving message from exchange. Error: %s", e.toString()));
        }
    }

    private final Set<ReceiverExchangeListener> listeners;

    public void addListener(ReceiverExchangeListener listener) {
        listeners.add(listener);
    }

    private void newMessage(String clientID, ReportMessage message) {
        Iterator<ReceiverExchangeListener> iterator = listeners.iterator();
        while (iterator.hasNext()) {
            iterator.next().newMessageForClient(clientID, message);
        }
    }

}
